package com.dawn.login.serviceimpl;

import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dawn.login.dao.LoginDao;
import com.dawn.login.service.LoginService;
import com.dawn.usermanage.bean.UserBean;
import com.dawn.usermanage.dao.UserManageDao;
import com.dawn.usermanage.service.UserManageService;
import com.dawn.utils.exceptions.DaoAccessException;

@Service
public class LoginServiceImpl implements LoginService {

	private static Logger logger = Logger.getLogger(LoginServiceImpl.class);

	@Autowired
	private LoginDao loginDAO;

	@Autowired
	private UserManageService userManageService;

	public UserBean findUser(String username, String password) {
		List<UserBean> users = null;
		try {
			users = loginDAO.findUser(username, password);
			if (!users.isEmpty()) {
				UserBean user = users.get(0);
				return user;
			}
		} catch (Exception e) {
			logger.error("Data access error!");
			e.printStackTrace();
			throw new DaoAccessException();
		}
		return null;
	}

	public boolean updateUserSinaInfo(String sinaId) {
		return false;
	}

	public void dealWithLogin(UserBean userBean) {
		try {
			Calendar lastLoginTime = userBean.getLastLoginTime();
			Calendar nowTime = Calendar.getInstance();
			if (nowTime.get(Calendar.DAY_OF_YEAR)
					- lastLoginTime.get(Calendar.DAY_OF_YEAR) > 0
					|| nowTime.get(Calendar.YEAR)
							- lastLoginTime.get(Calendar.YEAR) > 0) {
				userBean.setRemainNumByDay(30);
			}
			userBean.setLastLoginTime(nowTime);
			userManageService.updateUser(userBean);
		} catch (Exception e) {
			e.printStackTrace();
			throw new DaoAccessException();

		}
	}
}
